package com.tianbing.adlottery.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.AbstractCachingViewResolver;

import com.tianbing.adlottery.helper.SkinUtils;
import com.tianbing.adlottery.util.ControllerFormBean;
import com.tianbing.adlottery.util.UserSession;

/**
 * for create mockup purpose,use a dummy spring controller
 * 
 * @author conan
 * 
 */
public class LoginController extends SimpleFormController {
	static Logger logger = Logger.getLogger(LoginController.class);

	private SkinUtils skinUtils;

	AbstractCachingViewResolver viewResolver;

	// IPartyService partyService;
	// ------------------GET Request LifeCycle------------------
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		// Person party = new Person();
		ControllerFormBean fb = new ControllerFormBean();
		UserSession authorization = (UserSession) skinUtils.getUserAuthorization(request, null);
		if (authorization != null) {
			fb.setEmailAddr(authorization.getUserId());
			fb.setPassword("");
		}
		return fb;
	}

	/**
	 * guarded by loginValidator
	 * 
	 */
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
			BindException arg3) throws Exception {
		ControllerFormBean fb = (ControllerFormBean) command;
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		UserSession auth = skinUtils.setUserAuthorization(request, response, fb.getEmailAddr(), fb.getPassword(), true);

		String forwardAction = request.getParameter("forwardAction");
		// viewResolver.clearCache();
		// viewResolver.removeFromCache("home",request.getLocale());
		if (forwardAction != null) {
			logger.info("redirect to forwardAction=" + forwardAction);
			response.sendRedirect(forwardAction);
			return null;
		}
		return mv;
	}

	public void setSkinUtils(SkinUtils skinUtils) {
		this.skinUtils = skinUtils;
	}

	public static void setLogger(Logger logger) {
		LoginController.logger = logger;
	}

	public void setViewResolver(AbstractCachingViewResolver viewResolver) {
		this.viewResolver = viewResolver;
	}

}
